package com.example.demo.Gmail.imp;



import com.example.demo.Gmail.Handle.GmailHandle;
import com.example.demo.Gmail.service.GmailService;
import com.google.api.services.gmail.Gmail;
import com.google.api.services.gmail.model.ListMessagesResponse;
import com.google.api.services.gmail.model.Message;
import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.List;

@Service
public class GmailServiceImp implements GmailService {

    //业务拆分：1.service 2.userid 3.MimeMessage
    public Message sendMessage(Gmail service,
                               String userId,
                               MimeMessage emailContent)
            throws MessagingException, IOException {
        Message message = GmailHandle.createMessageWithEmail(emailContent);
        message = service.users().messages().send(userId, message).execute();
        return message;
    }

    @Override
    public  List<Message> listMessagesWithLabels(Gmail service, String userId,
                                                       List<String> labelIds) throws IOException, GeneralSecurityException {
        ListMessagesResponse response = service.users().messages().list(userId)
                .setLabelIds(labelIds).execute();
        List<Message> messages = new ArrayList<Message>();
        while (response.getMessages() != null) {
            messages.addAll(response.getMessages());
            if (response.getNextPageToken() != null) {
                String pageToken = response.getNextPageToken();
                response = service.users().messages().list(userId).setLabelIds(labelIds)
                        .setPageToken(pageToken).execute();
            } else {
                break;
            }
        }
        return messages;
    }
   @Override
    public void deleteOne(Gmail service, String userId, String Id)
            throws IOException {
     service.users().messages().delete(userId,Id).execute();
    }

    @Override
    public void batchDelete(Gmail service, String userId,String [] Ids) throws IOException {
        for (String id:Ids){
            this.deleteOne(service,userId,id);
        }
    }
}
